package top.magicpotato.fast.quartz.job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import top.magicpotato.fast.quartz.exception.JobNotExisting;
import top.magicpotato.fast.quartz.utils.SpringContextUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author ycl
 * 执行任务的 job
 */
public class StdJob implements Job {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private Method method;

    private Object beanObj;

    private String beanName;

    private String className;

    private String methodName;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.debug("quartz Scheduled 开始执行");
        try {
            if (method == null || beanObj == null) {
                Class<?> beanClass = Class.forName(className);
                beanObj = SpringContextUtil.getBean(beanName);
                method = beanClass.getMethod(methodName);
            }

            // 执行目标方法
            method.invoke(beanObj);
        } catch (ClassNotFoundException | NoSuchMethodException | BeansException e) {
            throw new JobNotExisting(className + "." + methodName + " 任务不存在");
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }
}
